package com.huarui.companypackage.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.huarui.company.model.CompanyMarket;
import com.huarui.companypackage.dao.ICompanyMarketDao;
import com.huarui.companypackage.util.CompanyPackageConstant;
import com.huarui.market.dao.IMarketDao;
import com.huarui.market.model.Market;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
/**
 * 保险公司购买套餐,companyMarket保存规则
 * @author Administrator
 *
 */
public class CompanyMarket4InsuranceService implements CompanyMarketByCompanyTypeService{

	private IMarketDao marketDao;
	private ICompanyMarketDao companyMarketDao;
	@Override
	public Map<String,List<CompanyMarket>> getCompanyMarket4CompanyByType(List<String> marketIds,int duration,Integer mainMarketId){
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Integer companyId = sessionMessage.getCompanyId();
		List<CompanyMarket> companyAddedMarkets = new ArrayList<CompanyMarket>();
		List<CompanyMarket> companyUpdateMarkets = new ArrayList<CompanyMarket>();
		//保险公司
		CompanyMarket companyMarket = companyMarketDao.getAllCompanyMarketByCompanyId(companyId).get(0);
		if(companyMarket == null){
			//首次购买套餐
			Market insuranceMarket = marketDao.getMarketByMarketType(Market.MARKET_TYPE_INSURE).get(0);//保险市场
			//增加保险搜索市场
			CompanyMarket searchMarket = new CompanyMarket();
			searchMarket.setCompanyId(companyId);
			searchMarket.setDuration(duration);
			searchMarket.setMarketId(insuranceMarket.getId());
			searchMarket.setSearchable(CompanyMarket.SEARCHABLE);
			searchMarket.setBefore(false);
			companyAddedMarkets.add(searchMarket);
		}else{
			//更新保险公司的companyMarket
			//当前购买时间(数据库时间)
			Date curDay = companyMarketDao.getCurDay();
			//当前使用套餐到期时间
			Date overDue = companyMarket.getGmtEnd();
			//判断下一个套餐购买时前一个套餐是否已到期
			int daysBetween = curDay.compareTo(overDue);
			if(daysBetween <= 0){
				//套餐未到期前购买套餐，更新该companyMarket的gmtEnd,gmtModify
				companyMarket.setDuration(duration);
				companyMarket.setGmtEnd(companyMarket.getGmtEnd());
				companyMarket.setBefore(true);
			}else if(daysBetween > 0){
				//套餐已过期再购买套餐,更新gmtBegin,gmtEnd,gmtModify
				companyMarket.setDuration(duration);
				companyMarket.setBefore(false);
			}
			companyUpdateMarkets.add(companyMarket);
		}
		Map<String,List<CompanyMarket>> map = new HashMap<String, List<CompanyMarket>>();
		map.put(CompanyPackageConstant.COMPANYADDEDMARKETS.getType(), companyAddedMarkets);
		map.put(CompanyPackageConstant.COMPANYUPDATEMARKETS.getType(),companyUpdateMarkets);
		return map;
	}

	public void setMarketDao(IMarketDao marketDao) {
		this.marketDao = marketDao;
	}

	public void setCompanyMarketDao(ICompanyMarketDao companyMarketDao) {
		this.companyMarketDao = companyMarketDao;
	}

	
}
